package com.lagou.model;

import com.lagou.util.HttpProtocolUtil;
import com.lagou.util.StaticResourceUtil;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Kirito
 * @description: 封装服务器返回的Http响应信息
 * @date 2020/04/24
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 返回静态资源文件，根据请求的url获取静态文件的绝对路径，
     * 若静态资源文件存在，则通过IO操作读取文件内容并返回
     * 否则，返回404
     *
     * @param url String
     */
    public void outPutStaticResource(String url) throws IOException {
        // 获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(url);
        // 判断文件是否存在，存在输出，不存在返回404
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            StaticResourceUtil.outputStaticResource(file, outputStream);
        } else {
            outPutContent(HttpProtocolUtil.getHttpHeader404());
        }
    }

    /**
     * 返回Http响应格式字符串
     *
     * @param content String
     * @throws IOException IOException
     */
    public void outPutContent(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
